package com.studio.framework.controller.monitorSystem.service;

import com.studio.framework.controller.monitorSystem.bean.ServerGroup;
import com.studio.framework.controller.monitorSystem.dao.ServerGroupDao;
import com.studio.framework.controller.monitorSystem.dto.FindMonitorResDto;
import com.studio.framework.controller.monitorSystem.dto.ServerGroupDto;
import com.studio.framework.controller.monitorSystem.repository.ServerGroupRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Author jujh
 * @Date 2018/7/23
 */
@Service
public class ServerGroupService {

    @Autowired
    private ServerGroupRepository serverGroupRepository;

    @Autowired
    private ServerGroupDao serverGroupDao;

    @Autowired
    private ServerService serverService;


    /**
     * 条件查询所有的服务
     *
     * @return
     */
    public List<ServerGroup> findAllByCondition() {
        Sort sort = new Sort(Sort.Direction.DESC, "createDate");
        return serverGroupRepository.findAll(sort);

    }

    /**
     * add
     *
     * @return
     */
    public String create(ServerGroupDto createGroupDto) {
        ServerGroup serverGroup = new ServerGroup();
        BeanUtils.copyProperties(createGroupDto, serverGroup);
        serverGroup.setCreateDate(new Date());
        serverGroup = serverGroupRepository.save(serverGroup);
        return serverGroup.getId();
    }

    /**
     * update
     *
     * @return
     */
    public int update(ServerGroupDto updateGroupDto) {
        ServerGroup serverGroup = findById(updateGroupDto.getId());
        if (serverGroup == null) {
            return 1;
        } else {
            BeanUtils.copyProperties(updateGroupDto, serverGroup);
            serverGroupRepository.save(serverGroup);
        }
        return 0;
    }

    /**
     * delete
     *
     * @return
     */
    public String delete(String id) {
        ServerGroup serverGroup = findById(id);
        if (serverGroup == null) {
            return "未查询到分组";
        } else {
            //查询组下是否存在服务
            long serverCount = serverService.count(id);
            if (serverCount != 0) {
                return "分组下存在服务，不能删除";
            } else {
                serverGroupRepository.delete(id);
            }
        }
        return "0";
    }

    /**
     * 查询详情
     *
     * @return
     */
    public ServerGroup findById(String id) {
        ServerGroup serverGroup = serverGroupRepository.findOne(id);
        return serverGroup;
    }

    /**
     * update
     *
     * @return
     */
    public String update() {
        return null;
    }

    public List<FindMonitorResDto> findMonitorData() {
        return serverGroupDao.findMonitorData();
    }


}
